'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: dataset_handler.py
* @Time: 2025/11/12
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass
from uuid import UUID

from anyio import sleep, sleep_forever
from flask import request
from injector import inject
from internal.schema.dataset_schema import GetDatasetResp, UpdateDatasetReq, GetDatasetsWithPageReq, \
    GetDatasetsWithPageResp, CreateDatasetReq, HitReq, GetDataQueriesResp
from internal.service import  DatasetService
from pkg.paginator.paginator import PageModel
from pkg.response.response import success_json, success_message, validate_error_json
from pkg.sqlalchemy import SQLAlchemy


@inject
@dataclass
class DatasetHandler:
    """知识库处理器"""
    dataset_service: DatasetService
    db: SQLAlchemy

    def create_dataset(self):
        """创建知识库"""
        # 1.提取请求并校验
        req = CreateDatasetReq()
        if not req.validate():
            return validate_error_json(req.errors)
        # 2.调用服务创建知识库
        self.dataset_service.create_dataset(req)
        # 3.返回成功调用提示
        return success_message("创建知识库成功")

    def get_dataset(self, dataset_id: UUID):
        """根据传递的知识库id获取详情"""
        dataset = self.dataset_service.get_dataset(dataset_id)
        resp = GetDatasetResp()
        return success_json(resp.dump(dataset))

    def update_dataset(self, dataset_id: UUID):
        """根据传递的知识库id+信息更新知识库"""
        # 1.提取请求并校验
        req = UpdateDatasetReq()
        if not req.validate():
            return validate_error_json(req.errors)
        # 2.调用服务创建知识库
        self.dataset_service.update_dataset(dataset_id, req)
        # 3.返回成功调用提示
        return success_message("更新知识库成功")

    def get_datasets_with_page(self):
        """获取知识库分页+搜索列表数据"""
        # 1.提取query数据并校验
        req = GetDatasetsWithPageReq(request.args)
        if not req.validate():
            return validate_error_json(req.errors)
        # 2.调用服务获取分页数据
        datasets, paginator = self.dataset_service.get_datasets_with_page(req)
        # 3.构建响应
        resp = GetDatasetsWithPageResp(many=True)
        return success_json(PageModel(list=resp.dump(datasets), paginator=paginator))


    def hit(self, dataset_id:UUID):
        """根据传递的的知识库id+query 执行召回测试"""
        #1、提取数据并校验
        req = HitReq()
        if not req.validate():
            return validate_error_json(req.errors)
        #2、调用服务并执行检索策略
        hit_result = self.dataset_service.hit(dataset_id, req)
        return success_json(hit_result)


    def get_dataset_queries(self, dataset_id:UUID):
        """根据传递的知识库id 最近的十条查询记录"""
        dataset_queries = self.dataset_service.get_dataset_queries(dataset_id)
        resp = GetDataQueriesResp(many=True)
        return success_json(resp.dump(dataset_queries))

